package controller

import (
	"encoding/json"
	"net/http"
)

// AppError 应用程序错误结构体
type AppError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Status  int    `json:"-"` // 不序列化，但用于HTTP状态码
}

// NewAppError 创建基础错误
func NewAppError() *AppError {
	return &AppError{
		Code:    "failed",
		Message: "failed",
		Status:  http.StatusBadRequest,
	}
}

// NewAppErrorWithMessage 创建带消息的错误
func NewAppErrorWithMessage(message string) *AppError {
	return &AppError{
		Code:    "failed",
		Message: message,
		Status:  http.StatusBadRequest,
	}
}

// NewAppErrorWithCodeAndMessage 创建带代码和消息的错误
func NewAppErrorWithCodeAndMessage(code, message string) *AppError {
	return &AppError{
		Code:    code,
		Message: message,
		Status:  http.StatusBadRequest,
	}
}

// ToResponse 将错误转换为HTTP响应
func (e *AppError) ToResponse() (int, []byte, error) {
	// 序列化错误为JSON
	jsonData, err := json.Marshal(e)
	if err != nil {
		return http.StatusInternalServerError, []byte(`{"code":"internal_error","message":"Failed to marshal error"}`), err
	}
	return e.Status, jsonData, nil
}
